// 获取应用实例
var app = getApp();

Page({
  data: {
    showCartDetail: false, //是否显示购物车
    classifySeleted: '', //左边当前项
    rightId: 'right0', //右边对应的菜品
    tableNum: '1', //桌号数
    menuLists: [],
    cart: {
      count: 0, //点餐数
      total: 0, //总价
    },
    userInfo: {
      nickName:"",
      avatarUrl:'',//微信用户头像的https地址
    },
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: false//wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },

  getUserProfile(e) {
    let _that=this;
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        // console.log(res)
        _that.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        //将登录信息添加到全局变量
        app.globalData.userInfo=res.userInfo
        wx.login({
          success: (res) => {      
            // console.log(res)    
            if(res.code){
              wx.request({
                      url: 'https://orders.linshiqiang.cn/api/login/logincheck',
                      data: {
                              code: res.code,
                              user_name:_that.data.userInfo.nickName,
                              user_img:_that.data.userInfo.avatarUrl,
                      },
                      method:'GET',
                      success: function(res) {
                                      // console.log(res)                               
                                      console.log("微信用户登录成功");
                                      app.globalData.userId=res.data.user_id  
                                      // console.log(res)                             
                      }
                     
                  })
              }
            }
          })

      }

    })
  },  
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  // 菜单和菜单分类
  getMenu: function () {
    let that = this
    wx.request({
      url: 'https://orders.linshiqiang.cn/api/Menu/list',
      success: function (res) {
        
        let categoryList = res.data.data.categoryList
        let menuLists = res.data.data.menuLists
        for (var j = 0; j < menuLists.length; j++) {
          for (let i = 0; i < menuLists[j].length; i++) {
            //遍历一下menuLists[j] 在menuLists[j][i]["menu_num"]=0
            menuLists[j][i]["menu_num"] = 0
            menuLists[j][i]["menu_score"] = 0
          }
        }
        var temp = []
        temp = categoryList
        for (var j = 0; j < menuLists.length; j++) {
          temp[j]["menuList"] = menuLists[j]
        }
        app.globalData.categoryMenuList = temp
        console.log(temp);
        that.setData({
          menuLists: app.globalData.categoryMenuList,
          cart: app.globalData.cart
        })
      },
    })
  },


  /**
   * +增加按钮
   */
  tapAddCart: function (e) {
    var menuId = e.currentTarget.dataset.menu_id; //所点击的菜品ID
    // 获取全局变量对应信息
    let appCategoryMenuList = app.globalData.categoryMenuList
    for (let i = 0; i < appCategoryMenuList.length; i++) {
      for (let j = 0; j < appCategoryMenuList[i].menuList.length; j++) {
        if (menuId == appCategoryMenuList[i].menuList[j].menu_id) {
          appCategoryMenuList[i].menuList[j].menu_num++;
          let num = appCategoryMenuList[i].menuList[j].menu_num;
          let price = appCategoryMenuList[i].menuList[j].menu_price;
          appCategoryMenuList[i].menuList[j].menu_score = price * num;
          app.globalData.cart.count++ //总数
        }
      }
    }
    let orderAdd = []
    for (let i = 0; i < appCategoryMenuList.length; i++) {
      for (let j = 0; j < appCategoryMenuList[i].menuList.length; j++) {
        if (appCategoryMenuList[i].menuList[j].menu_num >= 1) {
          orderAdd.push(appCategoryMenuList[i].menuList[j])
        }
      }
    }
    let totalPrice = 0 //总价
    for (let i = 0; i < orderAdd.length; i++) {
      totalPrice = totalPrice + orderAdd[i].menu_score
    }
    app.globalData.cart.total = totalPrice

    this.setData({
      menuLists: appCategoryMenuList,
      cart: app.globalData.cart,
      orderAdd: orderAdd,
    })
  },

  /**
   * -减按钮
   */
  tapMinusCart: function (e) {
    // console.log(e)
    var menuId = e.currentTarget.dataset.menu_id; //所点击的菜ID
    let appCategoryMenuList = app.globalData.categoryMenuList
    for (let i = 0; i < appCategoryMenuList.length; i++) {
      for (let j = 0; j < appCategoryMenuList[i].menuList.length; j++) {
        if (menuId == appCategoryMenuList[i].menuList[j].menu_id && appCategoryMenuList[i].menuList[j].menu_num != 0) {
          appCategoryMenuList[i].menuList[j].menu_num--;
          let num = appCategoryMenuList[i].menuList[j].menu_num;
          let price = appCategoryMenuList[i].menuList[j].menu_price;
          appCategoryMenuList[i].menuList[j].menu_score = price * num;
          app.globalData.cart.count--
        }
      }
    }

    let orderAdd = []
    for (let i = 0; i < appCategoryMenuList.length; i++) {
      for (let j = 0; j < appCategoryMenuList[i].menuList.length; j++) {
        if (appCategoryMenuList[i].menuList[j].menu_num >= 1) {
          orderAdd.push(appCategoryMenuList[i].menuList[j])
        }
      }
    }
    let totalPrice = 0 //总价
    if(orderAdd.length===0){
      app.globalData.cart.total=0
    }else{
      for (let i = 0; i < orderAdd.length; i++) {
        totalPrice=totalPrice+orderAdd[i].menu_num*orderAdd[i].menu_price
        app.globalData.cart.total =  totalPrice
      }
    }
    this.setData({
      menuLists: appCategoryMenuList,
      cart: app.globalData.cart,
      orderAdd: orderAdd,
    })
  },

  //点击清空购物车
  clearCart:function(){    
    let appCategoryMenuList = app.globalData.categoryMenuList
    for (let i = 0; i < appCategoryMenuList.length; i++) {
      for (let j = 0; j < appCategoryMenuList[i].menuList.length; j++) {
          appCategoryMenuList[i].menuList[j].menu_num = 0;
          let num =  appCategoryMenuList[i].menuList[j].menu_num; 
          let price = appCategoryMenuList[i].menuList[j].menu_price;
          appCategoryMenuList[i].menuList[j].menu_score = price * num;
          app.globalData.cart.count = 0 //总数为0
      }
    }
    app.globalData.cart.total = 0 //对全局变量为0
    app.globalData.cart.count = 0 //对全局变量为0
    this.setData({
      orderAdd:'',
      cart: app.globalData.cart,
      showCartDetail: false,
      menuLists: appCategoryMenuList,
    })
  },

  // 点击左侧分类显示对应菜单
  leftClickMenu(e) {
    this.setData({
      classifySeleted: e.currentTarget.dataset.id,
      rightId: 'right' + e.currentTarget.dataset.id
    })
  },

  //滑动右侧显示出对应信息
  rightScroll(e) {
    // console.log("111111", e)
    if (e.detail.scrollTop > 10 && !this.data.scrollDown) {
      this.setData({
        scrollDown: true
      });
    } else if (e.detail.scrollTop < 10 && this.data.scrollDown) {
      this.setData({
        scrollDown: false
      });
    }
    var scale = e.detail.scrollWidth / 570,
      scrollTop = e.detail.scrollTop / scale,
      h = 0,
      classifySeleted,
      len = this.data.menuLists.length;
    this.data.menuLists.forEach(function (item, i) {
      var _h = 70 + item.menuList.length * (46 * 3 + 20 * 2);
      if (scrollTop >= h - 100 / scale) {
        classifySeleted = item.category_id;
      }
      h += _h;
    });
    this.setData({
      classifySeleted: classifySeleted
    });
  },

    //显示购物车详情
    showCartDetail: function () {
      this.setData({
        showCartDetail: !this.data.showCartDetail
      });
    },

  //隐藏购物车详情
  hideCartDetail: function () {
    this.setData({
      showCartDetail: false
    });
  },
  //去结算跳转页面
  submit: function () {
    if(app.globalData.userInfo.nickName == '请点击头像登录' || app.globalData.userInfo.nickName == undefined || app.globalData.userInfo.nickName == ''){
      wx.showToast({
        title: '尚未登录，请先登录!',   
        icon: 'none',   
        duration: 2000//持续的时间  
      })
      this.getUserProfile()
      return false;
    }
		wx.navigateTo({
			url: '../order/order'
		})
	},


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.onHide(app.globalData.cart.total = 0 )
    this.onHide(app.globalData.cart.count = 0 )
    this.getMenu() //调用菜单和分类
    if(app.globalData.scene){
      this.setData({
        tableNum: app.globalData.scene
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }

})